import { RequestProductDetailById } from "@/api/product";
import { onMounted, useAttrs, type Ref } from "vue";
import { useRoute,useRouter } from "vue-router";
import { Toast } from "vant";
import { ref } from "vue";
// import { ActionBar, ActionBarIcon, ActionBarButton } from 'vant';
import type { IProduct } from "@/tyoes/types";
import { useCartStore } from "@/stores/cart";
import router from "@/router";
// const { cartList}=useCounterStore() //没有响应性
export const getProductDetailAll = () => {
  let productNum = ref(0);

  let productDetailImg: Ref<Array<IProduct>> = ref([]);
  let product: ref<IProduct> = ref({});
  const route = useRoute();
  let token = localStorage.getItem('TOKEN')
  const onClickLeft = () => history.back();
  // onMounted(()=>{
  //     console.log(route.params.id)
  // })
//   const onClickIcon = () => Toast("点击图标");
//   const onClickButton = () => Toast("点击按钮");

  const getProductDetail = async (id: number) => {
    let result = await RequestProductDetailById(id);
    let { resultInfo, resultCode } = result;
    if (resultCode == 1) {
      product.value = resultInfo;
      productDetailImg.value = resultInfo.list;
    }
  };
  onMounted(() => {
    let id = route.params.id;
    getProductDetail(id);
  });
  //添加商品
  const addCart = () => {
    if(token){
      //根据当前要添加商品，判断购物车数组中是否存在
    //如果商品存在数量加一
    productNum.value++

    const cartStore = useCartStore();
    let cartList = cartStore.cartList; //这样就不会失去响应性
    // console.log("购物车列表",cartList)
    // productNum.value=cartList.num
    let oldProduct = cartList.find(
      (item: IProduct) => item.id == product.value.id
    );
    if (oldProduct) {
      oldProduct.num++;
    } else {
      cartStore.addProduct({
        id: product.value.id,
        name: product.value.product,
        url: product.value.picture,
        price: product.value.price,
        num: 0,
        state: false,
      });
    }
 
    Toast.success("添加购物车成功");
    }
    else{
      router.push('/user')
    }
   
  }
//   const buyProduct=()=>{
//     const router=useRouter()
//     router.push({path:'/cart'})

//   }
  return {
    productNum,
    productDetailImg,
    product,
    onClickLeft,
    getProductDetail,
    onMounted,
    addCart,
    // buyProduct,
  }
}
